import matplotlib.pyplot as plt
import numpy as np

# 读取多项式信息
filename = 'resultD.txt'
f = open(filename, 'r')
line = f.readlines()
f.close()

lab = ['s', 'v']
cha = ['Position', 'Speed']
# 计算绘图
x = np.linspace(-0.5, 13.8, 800)
for i in [1, 3]:
    # 分别绘制 Distance 以及 Speed 各自与 Time 的关系图
    k = (i - 1) // 2
    plt.figure()
    coff = [float(s) for s in line[i].split()]
    n = len(coff)
    y = np.zeros(800, dtype=float)
    # 计算各点多项式值
    for j in range(n - 1, -1, -1):
        y = coff[j] + np.multiply(y, x)
    s1 = lab[k] + "= f(t)"
    plt.plot(x, y, "b-", label=s1)
    # 绘制水平座标轴
    z = np.zeros(800)
    plt.plot(x, z, "black", label=lab[k]+"=0")
    # 对速度关系图像,绘制 v=81 的水平线
    if k == 1:
        z2 = z + 81
        plt.plot(x, z2, "black", label="v=81")
    
    # 图例和注记
    s2 = "D. " + cha[k] + " " + lab[k] + " - Time t"
    plt.title(s2)
    plt.xlabel("Time t")
    plt.ylabel(cha[k] + " " + lab[k])
    plt.legend()

    # 图片保存至指定文件夹
    figurename = "../report/figure/D_Car" + cha[k] + ".png"
    plt.savefig(figurename)

print("Finish draw figures of D.")